import { detail, contractOrderDetail } from 'services/order'
import pathToRegexp from 'path-to-regexp';

export default {
  namespace: 'orderDetail',
  state: {
    currentItemDetail: {},
    currentContractDetail: {},
    isShowContractDetailModal: false
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        const match = pathToRegexp('/orderList/detail/:id').exec(pathname);
        if (match) {
          dispatch({
            type: 'resetDetail'
          })
          const id = match[1];
          dispatch({
            type: 'detail',
            payload: {
              id: id
            }
          })
        }
      })
    }
  },
  effects: {
    * detail({
      payload
    }, { select, call, put }) {
      const data = yield call(detail, payload.id);
      yield put({
        type: 'detailSuccess',
        payload: {
          currentItemDetail: data.result
        }
      })
    },
    * onShowContractDetail({
      payload
    }, { select, call, put }) {
      const currentItemDetail = yield select(({ orderDetail }) => orderDetail.currentItemDetail);
      const data = yield call(contractOrderDetail, currentItemDetail.id, payload.contractOrderId);
      yield put({
        type: 'detailSuccess',
        payload: {
          currentContractDetail: data.result
        }
      })
      yield put({ type: 'showContractDetailModal', payload: {} })
    }
  },
  reducers: {
    detailSuccess(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    resetDetail(state, { payload }) {
      return {
        ...state,
        ...payload,
        currentItemDetail:{}
      }
    },
    showContractDetailModal(state, { payload }) {
      return {
        ...state,
        ...payload,
        isShowContractDetailModal: true
      }
    },
    hideContractDetailModal(state, { payload }) {
      return {
        ...state,
        ...payload,
        isShowContractDetailModal: false
      }
    }
  }
}
